package com.app.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.app.common.Result;
import com.app.mapper.AreaMapper;
import com.app.mapper.CategoryMapper;
import com.app.mapper.CityMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.utils.CommonHelp;
import com.app.utils.TokenUtils;
import com.app.vo.BusinessSettledVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 商家入驻表
 *
 * @author 16693103420
 * @since 2024-01-26
 */
@RestController
@RequestMapping("/businessSettled")
public class BusinessSettledController {
    @Autowired
    private BusinessSettledService businessSettledService;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private CustomerServiceService customerServiceService;

    // 查询列表
    @GetMapping("/getBusinessSettledList")
    public Result getBusinessSettledList(@RequestParam(defaultValue = "0") Integer page,
                                         @RequestParam(defaultValue = "10") Integer limit, String businessName,
                                         String phone, Integer status, HttpServletRequest request,
                                         @RequestParam(required = false) Integer areaId) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if ("false".equals(userId)) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        BusinessSettledVo businessSettledVo = businessSettledService.getBusinessSettledList(page, limit, businessName, phone, status, user, areaId);
        return Result.success(businessSettledVo);
    }

    /**
     * 入驻
     *
     * @param id
     * @return
     */
    @GetMapping("/updateStatus")
    public Result updateStatus(Integer id, Integer status) throws Exception {
        return businessSettledService.updateStatus(id, status);
    }


    //根据id查询
    @GetMapping("/getBusinessSettledById")
    public Result getBusinessSettledById(Integer id) {
        BusinessSettledModel businessSettled = businessSettledService.getById(id);
        if (businessSettled.getType() != null) {
            CategoryModel categoryModel = categoryMapper.selectById(businessSettled.getType());
            if (categoryModel != null) {
                businessSettled.setTypeText(categoryModel.getName());
            }
        }
        if (StrUtil.isNotBlank(businessSettled.getAreaCode())) {
            List<String> list = JSON.parseObject(businessSettled.getAreaCode(), new TypeReference<List<String>>() {
            });
            businessSettled.setValue(list);
        }
        return Result.success(businessSettled);
    }

    //新增和修改
    @PostMapping("/addAndUpdateBusinessSettled")
    public Result addAndUpdateBusinessSettled(@RequestBody BusinessSettledModel businessSettledModel, HttpServletRequest request) {
//        String token = request.getHeader("token");
//        if (token == null) {
//            return Result.error(405, "token不存在");
//        }
//        String openid = TokenUtils.nothingness(token);
//        UserModel user = userService.getUserByOpenid(openid);
        UserModel user = userService.getUserByPhone(businessSettledModel.getPhone());
        if (user == null) {
            return Result.error(500, "请该手机号的用户先登录小程序后再进行入驻");
        }
//        List<CustomerServiceModel> list = customerServiceService.list();
//        CustomerServiceModel customerServiceModel = new CustomerServiceModel();
//        if (list != null || !list.isEmpty()) {
//            Integer count = 10000;
//            for (CustomerServiceModel model : list) {
//                if (model.getNowNum() < count) {
//                    customerServiceModel = model;
//                }
//            }
//        }
//        businessSettledModel.setCustomerServiceId(customerServiceModel.getId());
        if (businessSettledModel.getValue() != null) {
            businessSettledModel.setAreaCode(JSON.toJSONString(businessSettledModel.getValue()));
        } else {
            List<String> value = new ArrayList<>();
            QueryWrapper<CityModel> cityModelQueryWrapper = new QueryWrapper<>();
            cityModelQueryWrapper.eq("city_id", businessSettledModel.getCityId());
            CityModel cityModel = cityMapper.selectOne(cityModelQueryWrapper);
            value.add(cityModel.getProvinceId().toString());
            value.add(businessSettledModel.getCityId());
            value.add(businessSettledModel.getAreaId());
            businessSettledModel.setAreaCode(JSON.toJSONString(value));
        }
        businessSettledModel.setUserId(user.getId());
        businessSettledModel.setCreateTime(CommonHelp.getNowTimestamp());
        businessSettledModel.setUpdateTime(CommonHelp.getNowTimestamp());
        if (businessSettledModel.getId() == null) {
            businessSettledModel.setStatus(2);
            businessSettledService.save(businessSettledModel);
        } else {
            businessSettledService.updateById(businessSettledModel);
        }
        return Result.success("添加成功");
    }
    //根据id删除
    @GetMapping("/delBusinessSettled")
    public Result delBusinessSettled(Integer id) {
        businessSettledService.removeById(id);
        return Result.success("删除成功");
    }

//
//    /**
//     * 更新状态
//     *
//     * @param id     id
//     * @param status 状态
//     * @return {@link Result}
//     */
//    @GetMapping("/updateStatus")
//    public Result updateStatus(Integer id, Integer status) {
//        BusinessSettledModel settledModel = businessSettledService.getById(id);
//        if (settledModel != null) {
//            settledModel.setStatus(status);
//            businessSettledService.updateById(settledModel);
//            return Result.success("更新成功");
//        }else {
//            return Result.success("");
//        }
//    }
}

